package com.amc.framework.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author ZhangXX
 * @date @2021/9/7 10:54
 */
@Configuration
public class ThreadPoolConfig {
    // 核心线程池大小
    @Value("${threadPool.corePoolSize}")
    private int corePoolSize;
    // 最大可创建的线程数
    @Value("${threadPool.maxPoolSize}")
    private int maxPoolSize;
    // 队列最大长度
    @Value("${threadPool.queueCapacity}")
    private int queueCapacity;
    // 线程池维护线程所允许的空闲时间
    @Value("${threadPool.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }


}
